<template>
  <div class="app-container" style="padding: 10px">
    <el-card class="box-card" shadow="false">
      <el-form v-show="showSearch" ref="queryForm" :model="queryParams" :inline="true" label-width="80px">
        <el-form-item label="考试标题" prop="title">
          <el-input
            v-model="queryParams.id"
            placeholder="请输入考试标题"
            clearable
          />
        </el-form-item>
        <el-form-item label="试卷名称" prop="testPaperName">
          <el-input
            v-model="queryParams.testPaperName"
            placeholder="请输入试卷名称"
            clearable
          />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" icon="el-icon-search" @click="handleQuery"> 搜索</el-button>
          <el-button icon="el-icon-refresh" @click="resetQuery"> 重置</el-button>
        </el-form-item>
      </el-form>

      <el-row :gutter="10" class="mb8">
        <el-col :span="1.5">
          <el-button
            type="primary"
            icon="el-icon-plus"
            size="small"
            @click="handleAdd"
          >
            发布考试任务
          </el-button>
        </el-col>
        <right-toolbar :show-search.sync="showSearch" @queryTable="getList"/>
      </el-row>

      <el-table v-loading="loading" :data="dataList" border>
        <el-table-column label="ID" prop="id" width="200px" v-if="false"/>
        <el-table-column label="考试标题" prop="title"/>
        <el-table-column label="来源" prop="testPaperName" sortable>
          <template slot-scope="scope">
            {{scope.row.source === '1' ? '考试任务' : '培训考试任务'}}
          </template>
        </el-table-column>
        <el-table-column label="培训计划" prop="trainPlanName" />
        <el-table-column label="试卷名称" prop="testPaperName" width="260px" sortable>
          <template slot-scope="scope">
            {{ scope.row.testPaperId ? "《" + scope.row.testPaperName + "》" : "自定义试题" }}
          </template>
        </el-table-column>
        <el-table-column label="考试起止时间" width="260px" align="center">
          <template slot-scope="scope">
            <span v-if="scope.row.status === '0'">无</span>
            <div v-else>
              <div>
                <span>起始日期：{{ scope.row.startDate }}</span>
              </div>
              <div>
                <span>截止日期：{{ scope.row.endDate }}</span>
              </div>
            </div>
          </template>
        </el-table-column>
        <el-table-column label="备注" prop="remark" width="200px"/>
        <el-table-column label="创建人" prop="createBy" align="center"/>
        <el-table-column label="创建时间" prop="createTime" sortable width="160px" align="center"/>
        <el-table-column label="操作" width="200px" align="center">
          <template slot-scope="scope">
            <el-button
              icon="el-icon-view"
              size="mini"
              type="text"
              :disabled="scope.row.status === '0'"
              @click="handleInfo(scope.row.id)">
              评阅
            </el-button>
            <el-button
              icon="el-icon-delete"
              size="mini"
              type="text"
              :disabled="scope.row.status === '1'"
              @click="handleDelete(scope.row.id)"
            >
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <pagination
        v-show="total > 0"
        :limit.sync="queryParams.pageSize"
        :page.sync="queryParams.pageNum"
        :total="total"
        @pagination="getList"
      />


      <el-drawer :visible.sync="drawerShow" title="发布考试任务" size="40%">
        <div style="padding: 20px">
          <el-form ref="form" :model="params" :rules="rules" label-width="80px">
            <el-form-item label="考试标题" prop="title">
              <el-input v-model="params.title" placeholder="请输入考试标题"/>
            </el-form-item>
            <el-form-item label="试卷名称" prop="testPaperId">
              <el-select v-model="params.testPaperId" placeholder="请选择试卷名称" filterable style="width: 100%">
                <el-option v-for="item in testPapers"
                           :key="item.id"
                           :label="item.name"
                           :value="item.id"/>
              </el-select>
            </el-form-item>
            <el-form-item label="起止时间" prop="dateRange">
              <el-date-picker
                style="width: 100%"
                v-model="params.dateRange"
                value-format="yyyy-MM-dd"
                type="daterange"
                range-separator="至"
                start-placeholder="起始日期"
                end-placeholder="截止日期">
              </el-date-picker>
            </el-form-item>
            <el-form-item label="备注" prop="remark">
              <el-input type="textarea" v-model="params.remark" placeholder="请输入考试备注"/>
            </el-form-item>
            <el-form-item label="选择用户" prop="userIds">
              <el-select v-model="selectType" placeholder="请选择用户" clearable @change="selectTypeChange"
                         style="width: 100%">
                <el-option label="按部门选择" value="1"/>
                <el-option label="按角色选择" value="2"/>
                <el-option label="按用户选择" value="3"/>
              </el-select>
            </el-form-item>
            <div>
              <div v-if="selectType === '1'">
                <el-tree
                  :data="deptOptions"
                  :props="defaultProps"
                  :expand-on-click-node="false"
                  ref="tree"
                  node-key="id"
                  default-expand-all
                  highlight-current
                  show-checkbox
                />
              </div>
              <div v-if="selectType === '2'">
                <el-table
                  :data="roleList"
                  border
                  highlight-current-row
                  @current-change="handleCurrentChange"
                  @selection-change="handleRoleSelectionChange"
                  size="mini"
                  height="400">
                  <el-table-column type="selection" width="55" align="center"/>
                  <el-table-column prop="roleName" label="角色名称" align="center"/>
                </el-table>
              </div>
              <div v-if="selectType === '3'">
                <el-table v-loading="userLoading" size="mini" :data="userList" @selection-change="handleSelectionChange"
                          height="400" border>
                  <el-table-column type="selection" width="55" align="center"/>
                  <el-table-column label="工号" prop="userName"/>
                  <el-table-column label="姓名" prop="nickName"/>
                  <el-table-column label="手机号码" prop="phonenumber"/>
                </el-table>
              </div>
            </div>
          </el-form>
          <div style="text-align: right; margin-top: 20px">
            <el-button @click="cancel">
              取 消
            </el-button>
            <el-button type="primary" @click="submit">
              保 存
            </el-button>
          </div>
        </div>
      </el-drawer>
    </el-card>
  </div>
</template>

<script>
import {testPaperList} from "@/api/exam/testPaper";
import {listUser} from "@/api/app/user";
import {listRole} from "@/api/app/role";
import {deptTreeSelect} from "@/api/system/user";
import {testTaskInfoAddOrUpdate, testTaskInfoDelete, testTaskInfoList} from "@/api/exam/testTaskInfo";

export default {
  name: 'taskInfo',
  data() {
    const checkUsers = (rule, value, callback) => {
      console.log("thisparams", this.params)
      if ((this.selectType === '2' || this.selectType === '3') && !this.params.userIds) {
        callback(new Error('请选择至少一个用户'))
      } else {
        callback()
      }
    };
    return {
      loading: false,
      showSearch: true,
      queryParams: {
        pageNum: 1,
        pageSize: 10
      },
      total: 0,
      dataList: [],
      drawerShow: false,
      params: {},
      testPapers: [],
      selectType: '',
      userLoading: false,
      userList: [],
      roleList: [],
      queryUserParams: {
        pageNum: 1,
        pageSize: 9999,
        userType: 'front_user'
      },
      deptOptions: undefined,
      defaultProps: {
        children: "children",
        label: "label",
      },
      rules: {
        title: [{
          required: true,
          message: '请输入考试任务标题',
          trigger: 'blur'
        }],
        testPaperId: [{
          required: true,
          message: '请选择试卷',
          trigger: 'blur'
        }],
        dateRange: [{
          required: true,
          message: '请选择考试起止时间',
          trigger: 'blur'
        }],
        userIds: [{
          required: true,
          validator: checkUsers,
          trigger: 'blur'
        }]
      }
    }
  },
  created() {
    this.handleQuery()
  },
  methods: {
    handleQuery() {
      this.queryParams.pageNum = 1
      this.getList()
    },
    resetQuery() {
      this.queryParams = {
        pageNum: 1,
        pageSize: 10
      }
      this.getList()
    },
    getList() {
      this.loading = true
      testTaskInfoList(this.queryParams).then(res => {
        this.dataList = res.rows
        this.total = res.total
        this.loading = false
      })
    },
    getTestPaperList() {
      testPaperList({
        pageNum: 1,
        pageSize: 9999
      }).then(res => {
        this.testPapers = res.rows
      })
    },
    getUserList() {
      this.userLoading = true
      listUser(this.queryUserParams).then(
        (response) => {
          this.userList = response.rows;
          this.userLoading = false
        }
      );
    },
    handleAdd() {
      this.getTestPaperList()
      this.drawerShow = true
    },
    selectTypeChange(e) {
      this.userList = []
      if (e === '1') {
        this.getDeptTree()
      }
      if (e === '2') {
        this.getRoleList()
      }
      if (e === '3') {
        this.getUserList()
      }
    },
    handleSelectionChange(selection) {
      this.params.userIds = selection.map(item => item.userId).toString()
    },
    handleRoleSelectionChange(selection) {
      this.params.userIds = selection.map(item => item.roleId).toString()
    },
    getRoleList() {
      listRole({
        pageNum: 1,
        pageSize: 9999
      }).then((response) => {
        this.roleList = response.rows;
      });
    },
    /** 查询部门下拉树结构 */
    getDeptTree() {
      deptTreeSelect().then((response) => {
        this.deptOptions = response.data;
      });
    },
    handleCurrentChange(e) {
      this.queryUserParams.roleId = e.id
      this.getUserList()
    },
    cancel() {
      this.drawerShow = false
      this.userList = []
      this.selectType = ''
      this.params = {}
    },
    submit() {
      this.$refs.form.validate(valid => {
        if (valid) {
          if (this.selectType === '1') {
            this.params.userIds = this.$refs.tree.getCheckedKeys().toString()
          }
          this.params.selectType = this.selectType
          this.params.startDate = this.params.dateRange[0]
          this.params.endDate = this.params.dateRange[1]
          console.log(this.params)
          testTaskInfoAddOrUpdate(this.params).then(res => {
            this.cancel()
            this.$message({
              type: 'success',
              message: '操作成功!'
            });
            this.getList()
          })
        }
      })
    },
    handleInfo(id) {
      this.$router.push({
        path: '/exam/testTask/index',
        query: {
          taskInfoId: id
        }
      })
    },
    handleDelete(id) {
      this.$confirm('是否删除该考试任务?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        testTaskInfoDelete(id).then(() => {
          this.handleQuery()
          this.$message({
            type: 'success',
            message: '删除成功!'
          });
        })
      })
    }
  }
}
</script>

<style scoped>

</style>
